﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Sok.Munkae.Core;
using Sok.Munkae.Core.DataInterfaces;
using Sok.Munkae.Tenant;

namespace Sok.Munkae.Data
{
    public class UserRepository : IUserRepository
    {
        #region Constructor

        private IDao<User> dao;
        private ITenantIdentifier tenantIdentifier;
        private int organizationId;
        private IOrganizationRepository organizationRepository;

        public UserRepository(ITenantIdentifier tenantIdentifier, IDao<User> dao, 
            IOrganizationRepository organizationRepository)
        {
            this.dao = dao;
            this.tenantIdentifier = tenantIdentifier;
            this.organizationRepository = organizationRepository;
            
        }

        #endregion

        public virtual User Get(int id)
        {
            throw new NotImplementedException();
        }

        public virtual IList<User> GetAll()
        {
            throw new NotImplementedException();
        }

        public virtual User GetByUserName(string userName)
        {
            return dao.GetOne(
                    "select Id,[UserName],[Password],OrganizationId FROM [User] WHERE UserName = @UserName AND OrganizationId = @OrganizationId",
                    new Dictionary<string, object>() {{"@UserName", userName}, {"@OrganizationId", tenantIdentifier.GetTenantId()}},
                    BuildOne);
        }
        

        
        //DEMO CODE QUALITY ALERT! Having this method in each repository is probably to repetitive, consider refactoring (DRY = "Don't Repeat Yourself")
        protected User BuildOne(IDataReader reader)
        {
            var organization = organizationRepository.Get(tenantIdentifier.GetTenantId());

            User user = new User(organization);
            while (reader.Read())
            {
                user.Id = (int) reader["Id"];
                user.UserName = (string) reader["UserName"];
                user.Password = (string) reader["Password"];

                if (reader.Read())
                {
                    //too many results returned
                    user = null;
                }
            }
            return user;
        }
    }
}
